package com.ironone.streaming;

import java.util.Arrays;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SlidingPaneLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.ironone.streaming.application.CusAlrtBtnTypes;
import com.ironone.streaming.application.CusAlrtIconTypes;
import com.ironone.streaming.application.CustomAlertDialog;
import com.ironone.streaming.application.FormObject;
import com.ironone.streaming.application.MainApplication;
import com.ironone.streaming.comm.HTTPManager;
import com.ironone.streaming.evt.CallEventHandler;
import com.ironone.streaming.exception.ExceptionHandler;
import com.ironone.streaming.lite.R;
import com.ironone.streaming.model.ModelMapper;
import com.ironone.streaming.model.NewsDataModel;
import com.ironone.streaming.model.OurShowsDataModel;
import com.ironone.streaming.model.ResponseDataModel;

public class MainMenuFragment extends Fragment {
	private UiLifecycleHelper uiHelper;
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;
	// public static NewsDataModel[] news_items;
	public static List<NewsDataModel> newsList;

	View view;
	SlidingPaneLayout mPane;
	LoginButton fbLoginButton;
	ImageView roundfb_profilepic;
	TextView textView_firstname;
	Button homebtn;
	TextView nowPlayingInfo_screenname;
	LinearLayout showNameBar;
	ImageView powered_by_blue_icon, powered_by_gray_icon;

	public static LinearLayout progress_bar_layout;
	public static boolean isNewsSelected = false;

	// Menu item1
	/*
	 * LinearLayout weeklypick_layout; TextView weeklypick_textView1; TextView
	 * weeklypick_textView2; LinearLayout weeklypick_ticker;
	 */

	// Menu item2
	LinearLayout events_layout;
	TextView events_textView1;
	TextView events_textView2;
	LinearLayout events_ticker;

	// Menu item3
	LinearLayout callus_layout;
	TextView callus_textView1;
	TextView callus_textView2;
	LinearLayout callus_ticker;

	// Menu item4
	LinearLayout ourshows_layout;
	TextView ourshows_textView1;
	TextView ourshows_textView2;
	LinearLayout ourshows_ticker;

	// Menu item5
	LinearLayout request_layout;
	TextView request_textView1;
	TextView request_textView2;
	LinearLayout request_ticker;

	// Menu item6
	public static LinearLayout news_layout;
	TextView news_textView1;
	TextView news_textView2;
	public static LinearLayout news_ticker;

	@Override
	public void onSaveInstanceState(Bundle outState) {
		try {
			super.onSaveInstanceState(outState);
			outState.putBoolean(PENDING_PUBLISH_KEY,
					pendingPublishReauthorization);
			uiHelper.onSaveInstanceState(outState);
			// uiHelper.onSaveInstanceState(outState);
		} catch (Exception e) {
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(
					getActivity()));
			uiHelper = new UiLifecycleHelper(getActivity(), callback);
			uiHelper.onCreate(savedInstanceState);
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(
					getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.mainmenu_fragment, container, false);
		try {
			mPane = (SlidingPaneLayout) getActivity().findViewById(R.id.pane);
			nowPlayingInfo_screenname = (TextView) getActivity().findViewById(
					R.id.nowPlayingInfo_screenname);
			showNameBar = (LinearLayout) getActivity().findViewById(
					R.id.showNameBar);
			powered_by_blue_icon = (ImageView) getActivity().findViewById(
					R.id.powered_by_blue_icon);
			powered_by_gray_icon = (ImageView) getActivity().findViewById(
					R.id.powered_by_gray_icon);

			fbLoginButton = (LoginButton) view.findViewById(R.id.fbLoginButton);
			fbLoginButton.setPublishPermissions(Arrays.asList(new String[] {
					"user_likes", "user_birthday", "email", "user_location" }));
			fbLoginButton.setBackgroundResource(R.drawable.facebookloginbutton);
			roundfb_profilepic = (ImageView) view
					.findViewById(R.id.roundfb_profilepic);
			textView_firstname = (TextView) view
					.findViewById(R.id.textView_firstname);
			homebtn = (Button) view.findViewById(R.id.homebtn);

			homebtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					aniamteScreeningText(" "); // Send space char if nothing to
												// display.
					if (nowPlayingInfo_screenname.getText().equals(" ")
							|| lastPane.equals(" ")) {
					} else {
						// aniamteScreeningText(" ");
						resetColors();
						showNameBar.setVisibility(View.INVISIBLE);
						powered_by_blue_icon.setVisibility(View.VISIBLE);
						powered_by_gray_icon.setVisibility(View.VISIBLE);
						getActivity()
								.getSupportFragmentManager()
								.beginTransaction()
								.replace(R.id.pane2, new AlbumArtFragment(),
										"pane2").commit();
					}
					mPane.closePane();
				}
			});

			fbLoginButton.setFragment(this);
			if (savedInstanceState != null) {
				pendingPublishReauthorization = savedInstanceState.getBoolean(
						PENDING_PUBLISH_KEY, false);
			}

			processMenu();
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(
					getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
		return view;
	}

	String lastPane = ""; // Updates in call_us section only

	private void processMenu() {
		try {
			int txtView1Size = (int) FormObject.getInstance().getTextSize();
			int txtView2Size = (int) (FormObject.getInstance().getTextSize() * 0.75);

			// Menu item1
			/*
			 * weeklypick_layout = (LinearLayout)
			 * view.findViewById(R.id.weeklypick_layout); weeklypick_textView1 =
			 * (TextView) view.findViewById(R.id.weeklypick_textView1);
			 * weeklypick_textView2 = (TextView)
			 * view.findViewById(R.id.weeklypick_textView2); weeklypick_ticker =
			 * (LinearLayout) view.findViewById(R.id.weeklypick_ticker);
			 * weeklypick_textView1.setTextSize(txtView1Size);
			 * weeklypick_textView2.setTextSize(txtView2Size);
			 * 
			 * weeklypick_layout.setOnTouchListener(new OnTouchListener() {
			 * 
			 * @Override public boolean onTouch(View v, MotionEvent event) {
			 * resetColors();
			 * weeklypick_ticker.setBackgroundColor(getResources()
			 * .getColor(R.color.orange_special)); return false; } });
			 * 
			 * weeklypick_layout.setOnClickListener(new OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { String val =
			 * getString(R.string.weekly_pick);
			 * if(nowPlayingInfo_screenname.getText().equals(val) ||
			 * lastPane.equals(val)){ }else { lastPane = "";
			 * aniamteScreeningText(val);
			 * getActivity().getSupportFragmentManager
			 * ().beginTransaction().replace(R.id.pane2, new
			 * WeeklyPickFragment(), "pane2").commit(); } mPane.closePane(); }
			 * });
			 */

			// Menu item2
			events_layout = (LinearLayout) view
					.findViewById(R.id.events_layout);
			events_textView1 = (TextView) view
					.findViewById(R.id.events_textView1);
			events_textView2 = (TextView) view
					.findViewById(R.id.events_textView2);
			events_ticker = (LinearLayout) view
					.findViewById(R.id.events_ticker);
			events_textView1.setTextSize(txtView1Size);
			events_textView2.setTextSize(txtView2Size);

			events_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					// events_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					// Helani
					// events_ticker.setBackgroundColor(getResources().getColor(R.color.blue_theme));
					events_ticker.setBackgroundDrawable(getResources()
							.getDrawable(
									R.drawable.menu_right_line_color_change));
					TransitionDrawable transition = (TransitionDrawable) events_ticker
							.getBackground();
					transition.startTransition(200);
					return false;
				}
			});

			events_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					events_ticker.setBackgroundColor(getResources().getColor(
							R.color.blue_theme));
					isNewsSelected = false;
					showNameBar.setVisibility(View.VISIBLE);
					powered_by_blue_icon.setVisibility(View.INVISIBLE);
					powered_by_gray_icon.setVisibility(View.INVISIBLE);
					String val = getString(R.string.events);
					if (nowPlayingInfo_screenname.getText().equals(val)
							|| lastPane.equals(val)) {
						aniamteScreeningText(val);
					} else {
						lastPane = "";
						aniamteScreeningText(val);
						getActivity()
								.getSupportFragmentManager()
								.beginTransaction()
								.replace(R.id.pane2, new EventsFragment(),
										"pane2").commit();
					}
					mPane.closePane();
				}
			});

			// Menu item3
			callus_layout = (LinearLayout) view
					.findViewById(R.id.callus_layout);
			callus_textView1 = (TextView) view
					.findViewById(R.id.callus_textView1);
			callus_textView2 = (TextView) view
					.findViewById(R.id.callus_textView2);
			callus_ticker = (LinearLayout) view
					.findViewById(R.id.callus_ticker);
			callus_textView1.setTextSize(txtView1Size);
			callus_textView2.setTextSize(txtView2Size);

			callus_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					// callus_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					// Helani
					callus_ticker.setBackgroundDrawable(getResources()
							.getDrawable(
									R.drawable.menu_right_line_color_change));
					TransitionDrawable transition = (TransitionDrawable) callus_ticker
							.getBackground();
					transition.startTransition(200);
					return false;
				}
			});

			callus_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// Helani
					callus_ticker.setBackgroundColor(getResources().getColor(
							R.color.blue_theme));
					isNewsSelected = false;
					showNameBar.setVisibility(View.VISIBLE);
					powered_by_blue_icon.setVisibility(View.INVISIBLE);
					powered_by_gray_icon.setVisibility(View.INVISIBLE);
					lastPane = nowPlayingInfo_screenname.getText().toString();
					aniamteScreeningText(getString(R.string.call_us));

					CallEventHandler.getInsatance().setDjNum(
							getString(R.string.phone_no));
					CallEventHandler.getInsatance().callAlert(getActivity());
				}
			});

			// Menu item4
			ourshows_layout = (LinearLayout) view
					.findViewById(R.id.ourshows_layout);
			ourshows_textView1 = (TextView) view
					.findViewById(R.id.ourshows_textView1);
			ourshows_textView2 = (TextView) view
					.findViewById(R.id.ourshows_textView2);
			ourshows_ticker = (LinearLayout) view
					.findViewById(R.id.ourshows_ticker);
			ourshows_textView1.setTextSize(txtView1Size);
			ourshows_textView2.setTextSize(txtView2Size);

			ourshows_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					// ourshows_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					// Helani
					ourshows_ticker.setBackgroundDrawable(getResources()
							.getDrawable(
									R.drawable.menu_right_line_color_change));
					TransitionDrawable transition = (TransitionDrawable) ourshows_ticker
							.getBackground();
					transition.startTransition(200);
					return false;
				}
			});

			ourshows_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// Helani
					ourshows_ticker.setBackgroundColor(getResources().getColor(
							R.color.blue_theme));
					isNewsSelected = false;
					String val = getString(R.string.our_shows);
					showNameBar.setVisibility(View.VISIBLE);
					powered_by_blue_icon.setVisibility(View.INVISIBLE);
					powered_by_gray_icon.setVisibility(View.INVISIBLE);
					if (nowPlayingInfo_screenname.getText().equals(val)
							|| lastPane.equals(val)) {
						aniamteScreeningText(val);
					} else {
						lastPane = "";
						aniamteScreeningText(val);
						// Line below:testing request fragment Ui
						// getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane2,
						// new RequestFragment(), "pane2").commit();
						getActivity()
								.getSupportFragmentManager()
								.beginTransaction()
								.replace(R.id.pane2, new OurShowsFragment(),
										"pane2").commit();
					}
					mPane.closePane();
				}
			});

			// Menu item5
			request_layout = (LinearLayout) view
					.findViewById(R.id.request_layout);
			request_textView1 = (TextView) view
					.findViewById(R.id.request_textView1);
			request_textView2 = (TextView) view
					.findViewById(R.id.request_textView2);
			request_ticker = (LinearLayout) view
					.findViewById(R.id.request_ticker);
			request_textView1.setTextSize(txtView1Size);
			request_textView2.setTextSize(txtView2Size);

			request_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (FormObject.getInstance().getTNLId() == null
							|| FormObject.getInstance().getTNLId().equals("")
							|| getCurrentShowName() == null) {
						// Helani
						resetColors();
						request_ticker
								.setBackgroundDrawable(getResources()
										.getDrawable(
												R.drawable.menu_right_line_color_change));
						TransitionDrawable transition = (TransitionDrawable) request_ticker
								.getBackground();
						transition.startTransition(200);
						return false;
					}

					resetColors();
					// request_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					// Helani
					request_ticker.setBackgroundDrawable(getResources()
							.getDrawable(
									R.drawable.menu_right_line_color_change));
					TransitionDrawable transition = (TransitionDrawable) request_ticker
							.getBackground();
					transition.startTransition(200);
					return false;
				}
			});

			request_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// Helani
					request_ticker.setBackgroundColor(getResources().getColor(
							R.color.blue_theme));
					isNewsSelected = false;
					showNameBar.setVisibility(View.VISIBLE);
					powered_by_blue_icon.setVisibility(View.INVISIBLE);
					powered_by_gray_icon.setVisibility(View.INVISIBLE);
					String val = getString(R.string.request);
					/*
					 * if(nowPlayingInfo_screenname.getText().equals(val) ||
					 * lastPane.equals(val)){ }else { lastPane = "";
					 * aniamteScreeningText(val); }
					 */

					String msgData = "";
					if (FormObject.getInstance().getTNLId() == null
							|| FormObject.getInstance().getTNLId().equals("")) {
						msgData = getString(R.string.please_login_to_continue);
					}

					if (!FormObject.getInstance().getFbLoginStatus()) {
						msgData = getString(R.string.please_login_to_continue);
					}

					if (getCurrentShowName() == null) {
						msgData = getString(R.string.no_shows_to_request);
					}

					if (msgData.equals("")) {
						if (nowPlayingInfo_screenname.getText().equals(val)
								|| lastPane.equals(val)) {
							aniamteScreeningText(val);
						} else {
							lastPane = "";
							aniamteScreeningText(val); // Moved the code to top
							getActivity()
									.getSupportFragmentManager()
									.beginTransaction()
									.replace(R.id.pane2, new RequestFragment(),
											"pane2").commit();
						}
						mPane.closePane();
					} else {
						CustomAlertDialog alertDialog = new CustomAlertDialog(
								getActivity(), CusAlrtBtnTypes.OK,
								CusAlrtIconTypes.WIZERD);
						/*alertDialog.setTitleText(getActivity().getString(
								R.string.you_shall_not_pass));
						alertDialog.setMessageText(msgData);*/
						alertDialog.setTitleText(msgData);
						alertDialog.show();
					}
				}
			});

			// start (Helani)
			// Menu item6
			news_layout = (LinearLayout) view.findViewById(R.id.news_layout);
			news_textView1 = (TextView) view.findViewById(R.id.news_textView1);
			news_textView2 = (TextView) view.findViewById(R.id.news_textView2);
			news_ticker = (LinearLayout) view.findViewById(R.id.news_ticker);
			news_textView1.setTextSize(txtView1Size);
			news_textView2.setTextSize(txtView2Size);

			// Progress bar
			progress_bar_layout = (LinearLayout) view
					.findViewById(R.id.progress_bar_layout);

			news_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					news_ticker.setBackgroundDrawable(getResources()
							.getDrawable(
									R.drawable.menu_right_line_color_change));
					TransitionDrawable transition = (TransitionDrawable) news_ticker
							.getBackground();
					transition.startTransition(200);
					return false;
				}
			});

			news_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					news_ticker.setBackgroundColor(getResources().getColor(
							R.color.blue_theme));
					isNewsSelected = true;
					showNameBar.setVisibility(View.VISIBLE);
					powered_by_blue_icon.setVisibility(View.INVISIBLE);
					powered_by_gray_icon.setVisibility(View.INVISIBLE);
					String val = getString(R.string.news);
					if (nowPlayingInfo_screenname.getText().equals(val)) { // removed
																			// ||lastPane.equals(val)
						//aniamteScreeningText(val);
						//mPane.closePane();
						aniamteScreeningText(val);
						if (newsList.get(0).getTitle().equals("No news")) {
							new RssDataAsync(getActivity(), mPane).execute();
						}else{
							mPane.closePane();
						}

					} else {
						lastPane = "";
						aniamteScreeningText(val);
						if (newsList == null) {
							new RssDataAsync(getActivity(), mPane).execute();
						} else if (newsList.get(0).getTitle().equals("No news")) {
							new RssDataAsync(getActivity(), mPane).execute();
						} else {
							getActivity()
									.getSupportFragmentManager()
									.beginTransaction()
									.replace(R.id.pane2, new NewsFragment(),
											"pane2").commit();
							mPane.closePane();
						}
					}
					// mPane.closePane();
				}
			});
			// end (Helani)

		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(
					getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	private String getCurrentShowName() {
		List<OurShowsDataModel> showModel = FormObject.getInstance()
				.getShowsData();
		int currTime = FormObject.getInstance().getTime();
		int dayX = MainApplication.getDayIndex();

		for (int x = 0; x < showModel.size(); x++) {
			// if show is not casting on today it will be ignored
			if (!showModel.get(x).showDays[dayX])
				continue;

			if (showModel.get(x).showtime_start <= currTime
					&& showModel.get(x).showtime_end >= currTime) {
				return showModel.get(x).showName;
			}
		}
		return null;
	}

	Animation fadeIn;

	private void aniamteScreeningText(final String dText) {
		fadeIn = new AlphaAnimation(0, 1);
		fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
		fadeIn.setDuration(MainApplication.ANIME_DURATION);

		Animation fadeOut = new AlphaAnimation(1, 0);
		fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
		fadeOut.setDuration(MainApplication.ANIME_DURATION);
		fadeOut.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				nowPlayingInfo_screenname.setText(dText);
				nowPlayingInfo_screenname.setAnimation(fadeIn);
			}
		});
		nowPlayingInfo_screenname.startAnimation(fadeOut);
	}

	private void resetColors() {
		// weeklypick_ticker.setBackgroundColor(getResources().getColor(R.color.gray_dark));
		events_ticker.setBackgroundColor(getResources().getColor(
				R.color.gray_light));
		callus_ticker.setBackgroundColor(getResources().getColor(
				R.color.gray_light));
		ourshows_ticker.setBackgroundColor(getResources().getColor(
				R.color.gray_light));
		request_ticker.setBackgroundColor(getResources().getColor(
				R.color.gray_light));
		news_ticker.setBackgroundColor(getResources().getColor(
				R.color.gray_light));
	}

	@Override
	public void onPause() {
		try {
			super.onPause();
			uiHelper.onPause();
		} catch (Exception e) {
			/*
			 * CustomAlertDialog alertDialog = new
			 * CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK,
			 * CusAlrtIconTypes.DUCK);
			 * alertDialog.setTitleText(getString(R.string.what_the_duck_));
			 * alertDialog
			 * .setMessageText(getString(R.string.something_snapped));
			 * alertDialog.show();
			 */
		}
	}

	@Override
	public void onResume() {
		try {
			super.onResume();
			Session session = Session.getActiveSession();
			if (session != null && (session.isOpened() || session.isClosed())) {
				onSessionStateChange(session, session.getState(), null);
			}
			uiHelper.onResume();
		} catch (Exception e) {
			/*
			 * CustomAlertDialog alertDialog = new
			 * CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK,
			 * CusAlrtIconTypes.DUCK);
			 * alertDialog.setTitleText(getString(R.string.what_the_duck_));
			 * alertDialog
			 * .setMessageText(getString(R.string.something_snapped));
			 * alertDialog.show();
			 */
		}
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private void onSessionStateChange(final Session session,
			SessionState state, Exception exception) {
		try {
			if (state.isOpened()) {

				if (session.isOpened()) {
					FormObject.getInstance().setFbLoginStatus(true);
					if (pendingPublishReauthorization
							&& state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
						pendingPublishReauthorization = false;
					}

					if (textView_firstname.getText().toString()
							.equals(getString(R.string.stranger)))
						new SyncFacebookDataAsync().execute();

					fbLoginButton
							.setBackgroundResource(R.drawable.menufblogoutbutton); // Logout
																					// image
				}

			} else if (state.isClosed()) {
				FormObject.getInstance().setFbLoginStatus(false);
				session.closeAndClearTokenInformation();

				Bitmap drfault_bm = BitmapFactory.decodeResource(
						getResources(), R.drawable.default_profile_pic);
				Bitmap img1 = MainApplication.getRoundedRectBitmap(
						getActivity(), drfault_bm, true);
				roundfb_profilepic.setImageBitmap(img1);
				textView_firstname.setText(R.string.stranger);

				/*
				 * if(FormObject.getInstance().getFbLoginStatus())
				 * fbLoginButton.
				 * setBackgroundResource(R.drawable.menufblogoutbutton); //
				 * Logout image else
				 */
				fbLoginButton
						.setBackgroundResource(R.drawable.menufbloginbutton); // Login
																				// image
			}
		} catch (Exception e) {
			FormObject.getInstance().setFbLoginStatus(false);
			FormObject.getInstance().setIsOneTimeExecuted(false);
			session.closeAndClearTokenInformation();

			Bitmap drfault_bm = BitmapFactory.decodeResource(getResources(),
					R.drawable.default_profile_pic);
			Bitmap img1 = MainApplication.getRoundedRectBitmap(getActivity(),
					drfault_bm, true);
			roundfb_profilepic.setImageBitmap(img1);
			textView_firstname.setText(R.string.stranger);

			fbLoginButton.setBackgroundResource(R.drawable.menufbloginbutton); // Login
																				// image

			// Toast.makeText(getActivity(), R.string.error_fb_general,
			// Toast.LENGTH_SHORT).show();
			CustomAlertDialog alertDialog = new CustomAlertDialog(
					getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.BIRD);
			alertDialog
			.setTitleText(getString(R.string.error_fb_general));
			/*alertDialog
					.setTitleText(getString(R.string.pigeon_s_taken_an_arrow));
			alertDialog.setMessageText(getString(R.string.error_fb_general));*/
			alertDialog.show();
		}
	}

	public class SyncFacebookDataAsync extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				if (FormObject.getInstance().getFbLoginStatus()) {
					MainApplication.getFacebookProfileData(getActivity());

					// If TNL id is null, then do this again and get a TNL id.
					// save it in FO
					if (FormObject.getInstance().getTNLId() == null
							|| FormObject.getInstance().getTNLId().equals(""))
						return sendFacebookDataToTNL();
				}
				return true;
			} catch (Exception e) {
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			if (FormObject.getInstance().getFbProfilePicture() != null) {
				Bitmap convImg = MainApplication.getByteArrToBitmap(FormObject
						.getInstance().getFbProfilePicture());
				Bitmap img = MainApplication.getRoundedRectBitmap(
						getActivity(), convImg, false);
				if (img != null)
					roundfb_profilepic.setImageBitmap(img);
				else {
					Bitmap drfault_bm = BitmapFactory.decodeResource(
							getResources(), R.drawable.default_profile_pic);
					Bitmap img1 = MainApplication.getRoundedRectBitmap(
							getActivity(), drfault_bm, true);
					roundfb_profilepic.setImageBitmap(img1);
				}
			} else {
				// Put the default image here
				Bitmap drfault_bm = BitmapFactory.decodeResource(
						getResources(), R.drawable.default_profile_pic);
				Bitmap img1 = MainApplication.getRoundedRectBitmap(
						getActivity(), drfault_bm, true);
				roundfb_profilepic.setImageBitmap(img1);
			}

			// String ss = FormObject.getInstance().getFbName();
			if (FormObject.getInstance().getFbName() != null
					&& FormObject.getInstance().getFbName() != "")
				textView_firstname.setText(FormObject.getInstance().getFbName()
						.split(" ")[0]);
			else
				textView_firstname.setText(R.string.stranger);
		}
	}

	private boolean sendFacebookDataToTNL() {
		try {
			HTTPManager httpmanager = new HTTPManager(getActivity());
			ResponseDataModel responseModel = httpmanager
					.sendFacebookUserData();

			if (responseModel.isError && responseModel.responseData == null) {
				return false;
			}

			if (ModelMapper.getLoginDataModel(responseModel) == null) {
				return false;
			} else {
				// Success
				MainApplication.foSaveChanges(getActivity());
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}
}